import { CreepsConfig } from '../../game/global'
import { LogHelper } from "../../utils/logHelper";

export class SourceTask implements IOuterOreTask{
  run(room: Room, closestRoom: Room): void {
    if(!room){
      return;
    }
    // 控制每10tick检查一次
    if(!room.memory.outerOreSourceCheckLastTime || ((Game.time - room.memory.outerOreSourceCheckLastTime) > 10)){
      // 取房间内可采集的资源
      const sources = room.find(FIND_SOURCES);
      for(const source of sources) {

        // 查找当前房间有没有外矿采集的虫子
        const roomCreeps = room.find(FIND_MY_CREEPS).filter((creep) => {
          return creep.memory.source && creep.memory.source.id === source.id && creep.memory.role === 'harvesterSourc'
        });
        // 查找附近房间有没有外矿采集的虫子
        const closestRoomCreeps = closestRoom.find(FIND_MY_CREEPS).filter((creep) => {
          return creep.memory.source && creep.memory.source.id === source.id && creep.memory.role === 'harvesterSourc'
        });
        // 查找孵化队列中有没有外矿采集的虫子
        if(!closestRoom.memory.spawnQueue){
          closestRoom.memory.spawnQueue = new Array<{ id:number,role:string,body:BodyPartConstant[],memory:CreepMemory }>();
        }
        const queueCreeps = closestRoom.memory.spawnQueue.filter((creep)=>{
          return creep.memory.source && creep.memory.source.id === source.id && creep.memory.role === 'harvesterSourc'
        });

        if(roomCreeps.length === 0 && closestRoomCreeps.length === 0 && queueCreeps.length === 0 && !closestRoom.find(FIND_MY_SPAWNS)[0].spawning){
          // 取出closestRoom等级并且生成对应等级的harvesterSourc
          const role = 'harvesterSourc';
          const body = closestRoom.calculateCreepBody({
            [WORK]: 0.6,
            [MOVE]: 0.3,
            [CARRY]: 0.1,
          },1000);
          closestRoom.spawnQueueAdd(role,body,{ role, bornRoom:closestRoom.name, source: { id:source.id,pos:source.pos }});
          LogHelper.log(`外矿房间管理[${room.name}] 申请孵化 ${role}`);
        }
      }
      room.memory.outerOreSourceCheckLastTime = Game.time;
    }
  }
}